package com.leviassaf.androidbasics;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

//67
public class GFXSurface extends Activity implements OnTouchListener {
	
	CustomAnimationViewSurface ourSurfaceView;
	float fltX, fltY;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ourSurfaceView = new CustomAnimationViewSurface(this);
		//71
		ourSurfaceView.setOnTouchListener(this);
		fltX = fltY = 0;
		setContentView(ourSurfaceView);

		this.setTitle(String.format("%s-%s", this.getTitle().toString(), this.getClass().getSimpleName()));
	}

	//70
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		ourSurfaceView.pause();
	}

	//70
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ourSurfaceView.resume();
	}

	//71
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		fltX = event.getX();
		fltY = event.getY();
		//73
		return true;
	}

	//67
	public class CustomAnimationViewSurface extends SurfaceView implements Runnable {
		
		//68
		SurfaceHolder surfaceholder;
		Thread thread = null;
		
		//69-71
		boolean booIsRunning = false;

		public CustomAnimationViewSurface(Context context) {
			super(context);
			surfaceholder = getHolder();
		}
		
		//70
		public void pause(){
			booIsRunning = false;
			while(true){
				try {
					thread.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
			thread = null;
		}
		
		//70
		public void resume(){
			booIsRunning = true;
			thread = new Thread(this);
			thread.start();
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			//69
			while (booIsRunning){
				if (!surfaceholder.getSurface().isValid()){
					continue;
				}
				Canvas canvas = surfaceholder.lockCanvas();
				canvas.drawRGB(45, 200, 103);
				
				//72
				if (fltX != 0 && fltY != 0){
					Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.globe);
					canvas.drawBitmap(bmp, fltX - (bmp.getWidth() / 2), fltY - (bmp.getHeight() / 2), null);
				}
				
				surfaceholder.unlockCanvasAndPost(canvas);
			}
		}

	}
}
